package com.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.entity.ShoppingCart;
import com.bookstore.mapper.ShoppingCartMapper;
import com.bookstore.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public boolean addToCart(Integer userId, Integer bookId, Integer quantity) {
        // 检查是否已存在该商品
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId)
                .eq(ShoppingCart::getBookId, bookId);
        ShoppingCart existingItem = getOne(queryWrapper);

        if (existingItem != null) {
            // 更新数量
            existingItem.setQuantity(existingItem.getQuantity() + quantity);
            return updateById(existingItem);
        } else {
            // 新增购物车项
            ShoppingCart cartItem = new ShoppingCart();
            cartItem.setUserId(userId);
            cartItem.setBookId(bookId);
            cartItem.setQuantity(quantity);
            return save(cartItem);
        }
    }

    @Override
    public boolean updateQuantity(Integer cartId, Integer quantity) {
        ShoppingCart cartItem = getById(cartId);
        if (cartItem == null) {
            throw new IllegalArgumentException("购物车项不存在");
        }
        cartItem.setQuantity(quantity);
        return updateById(cartItem);
    }

    @Override
    public boolean removeFromCart(Integer cartId) {
        return removeById(cartId);
    }

    @Override
    public List<ShoppingCart> getUserCart(Integer userId) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId)
                .orderByDesc(ShoppingCart::getCreatedAt);
        return list(queryWrapper);
    }

    @Override
    public boolean clearCart(Integer userId) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        return remove(queryWrapper);
    }
} 